package com.example.demo01.demo;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.demo01.R;
import com.example.demo01.fragments.TitleFragment;
import com.example.demo01.utils.Utils;

import java.util.Arrays;
import java.util.Objects;

public class RequestPermissionsDemo extends AppCompatActivity {
    private ActivityResultLauncher<Intent> activityResultLauncher;
    Utils utils = new Utils(this);
    private AlertDialog dialog;
    private String RequestPermission;
    private Button btn_request_location_permissions, btn_request_mike_permissions;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_request_permissions);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        //. 添加标题
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.fl_title, TitleFragment.newInstance(getResources().getString(R.string.RequestPermissionsDemo)))
                .commit();

        initView();
    }

    //. 初始化视图
    private void initView() {
        btn_request_location_permissions = findViewById(R.id.btn_request_location_permissions);
        btn_request_mike_permissions = findViewById(R.id.btn_request_mike_permissions);

        addListener();
    }

    //. 添加点击事件
    private void addListener() {
        btn_request_location_permissions.setOnClickListener(v -> checkAndRequestPermission(Manifest.permission.ACCESS_FINE_LOCATION));
        btn_request_mike_permissions.setOnClickListener(v -> checkAndRequestPermission(Manifest.permission.RECORD_AUDIO));


        //. 注册结果回调
        activityResultLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    //. 设置完毕以后，就重新验证权限
                    int i = checkSelfPermission(RequestPermission);
                    if (i == PackageManager.PERMISSION_GRANTED) {
                        initData();
                    } else {
                        utils.showToast("权限请求失败");
                    }
                });
    }

    //. 检查权限并请求权限
    private void checkAndRequestPermission(String permission) {
        //. 方便前往设置返回结果后检查
        if (!Objects.equals(RequestPermission, permission)) RequestPermission = permission;
        //. 检查精准定位权限
        int checkResult = checkSelfPermission(permission);

        if (checkResult == PackageManager.PERMISSION_GRANTED) {
            //. 已经授权
            initData();
        } else {
            //. 没有授权
            //. 第一个参数：权限的数组
            //. 第二个参数：请求码
            requestPermissions(new String[]{permission}, 1);
        }
    }


    //. 处理权限请求结果
    //- 参数：requestCode(请求码)、permissions(权限数组)、grantResults(授权结果数组)
    //! 注意：使用这个回调函数时参数中不能包含 deviceId 设备码，自动生成函数时会自带这个形参务必删除
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 1) {
            int result = grantResults[0];
            if (result == PackageManager.PERMISSION_GRANTED) {
                initData();

            } else {
                showPermission();
            }
        }
    }


    //. 显示权限设置对话框
    private void showPermission() {
        if (dialog == null || !dialog.isShowing()) {
            dialog = new AlertDialog.Builder(this)
                    .setTitle("权限申请")
                    .setMessage("请在设置—应用—" + getString(R.string.app_name) + "—权限中开启相应权限")
                    .setCancelable(false)
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            finish();
                        }
                    })
                    .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            //. 通过一个Intent去进入设置页面
                            startAppSetting();
                        }
                    }).show();
        }
    }

    //. 跳转到设置页面
    private void startAppSetting() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        //. 获取包名并设置数据
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);
        activityResultLauncher.launch(intent);
    }


    //. 模拟数据初始化
    private void initData() {
        utils.showToast("权限请求成功,正在初始化数据...");
    }


}